package com.nongtai.interceptor;

import com.nongtai.constant.JwtClaimsConstant;
import com.nongtai.constant.RedisConstant;
import com.nongtai.context.BaseContext;
import com.nongtai.properties.JwtProperties;
import com.nongtai.result.Result;
import com.nongtai.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author yza
 * @version 1.0
 * @date 2024/7/16 15:54
 */
@Component
@Slf4j
public class JwtTokenInterceptor implements HandlerInterceptor {
    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private JwtProperties jwtProperties;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        try {
            // 从请求头获取token
            String token = request.getHeader(jwtProperties.getUserTokenName());
            String[] tokenSplit = token.split(" ");
            if ("Bearer".equals(tokenSplit[0])){
                // 解析token
                Claims claims = jwtUtil.parseJWT(tokenSplit[1]);
                // 获取当前请求的userid
                Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
                // 检查当前携带的token是否最新
                String currentToken = (String)redisTemplate.opsForHash().get(RedisConstant.USER_SESSION, userId.toString());
                if(currentToken.equals(tokenSplit[1])){
                    // 将userid存储到啊threadLocal里
                    BaseContext.setCurrentId(userId);
                    return true;
                }else {
                    response.setStatus(401);
                    return false;
                }
            }
            return false;
        }catch (Exception e){
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.removeCurrentId();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
